package cn.com.callback

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;

/**
 * @author ThinkPad
 */

public class design implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(design.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        log.debug('==================================解密效验=================================================');
        try {
            def requestbody = Util.getRequestBody(request, "utf-8"); //获取报文
            JSONObject obj = JSONObject.fromObject(requestbody);
            def sign = obj.get("sign");    //获取签名
            obj.remove("sign"); //去除签名
            def secretkey = obj.get("secretkey"); //获取密钥
            obj.remove("secretkey"); //	去除密钥
            def mapStr = assemble(obj);    //原始Map拼接成：keyvalue...keyvalue格式
            def encryptstr = Util.getMD5Str(mapStr); // 第一次加密，拼接之后的原始字符串进行md5加密
            encryptstr = Base64.encode(encryptstr + secretkey, "utf-8"); // 第二次加密，base64加密，加上秘钥(由接收方提供)
            encryptstr = Util.getMD5Str(encryptstr); // 第三次加密，再次进行md5加密
            encryptstr = encryptstr.toUpperCase(); //转大写
            if (encryptstr == sign) {
                return 1;
            } else {
                return 0;
            }
        } catch (Exception e) {
            log.error("", e);
            return 0;
        }
    }

    public String assemble(JSONObject params) {
        // 1.sort：先按照map的key值进行排序
        Object[] keyArr = new Object[params.size()];
        params.keySet().toArray(keyArr);
        Arrays.sort(keyArr);

        // 2.拼接成：keyvalue...keyvalue字符串
        StringBuffer queryString = new StringBuffer();
        for (Object key : keyArr) {
            Object val = params.get(key);
            if (val != null) {
                queryString.append(key);
                if (val instanceof Boolean) {
                    boolean flag = (Boolean) val;
                    queryString.append(flag ? 1 : 0);
                } else {
                    queryString.append(val);
                }
            }
        }
        return queryString.toString();
    }

}